//
//  HJBlacklistController.m
//  KaiChat
//
//  Created by lx on 2023/11/27.
//

#import "HJBlacklistController.h"
#import "HJBlacklistCell.h"
#import "HJSectionHeaderView.h"
#import "HJIM.h"
#import "HJUserInfoController.h"
#import "HJMinePresent.h"
#import "TJEmptyDataHandler.h"
#import "HJButton.h"
#import "HJAlertController.h"

@interface HJBlacklistController ()

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, assign) BOOL isSelectAll;
@property (nonatomic, assign) BOOL isShowBottomView;

@property (nonatomic, weak) HJBarButton *editButton;
@property (nonatomic, weak) HJBarButton *selectAllButton;
@property (nonatomic, weak) UIView *buttoomView;
@property (nonatomic, strong) NSMutableArray *selectDatas;

@end

@implementation HJBlacklistController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"Blacklist";
    self.navigationBar.lineView.hidden = YES;
    
    [self.navigationBar.backBarButton setImage:[UIImage imageNamed:@"nav_close"] forState:UIControlStateSelected];
    
    HJBarButton *editButton = [HJBarButton barButtonWithTitle:@"Edit" color:UIColor.tj_333333Color target:self action:@selector(didClickEditButton)];
    [editButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [editButton sizeToFit];
    editButton.alpha = 0;
    CGSize buttonSize = editButton.tj_size;
    [self.navigationBar.contentView addSubview:editButton];
    [editButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(buttonSize.width);
        make.height.offset(40);
        make.centerY.offset(0);
    }];
    _editButton = editButton;
    
    HJBarButton *selectAllButton = [HJBarButton barButtonWithTitle:@"Select all" color:UIColor.tj_333333Color target:self action:@selector(didClickSelectAllButton:)];
    selectAllButton.hidden = YES;
    [selectAllButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [selectAllButton sizeToFit];
    buttonSize = selectAllButton.tj_size;
    [self.navigationBar.contentView addSubview:selectAllButton];
    [selectAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(buttonSize.width);
        make.height.offset(40);
        make.centerY.offset(0);
    }];
    _selectAllButton = selectAllButton;
    
    [self.tableView registerClass:HJBlacklistCell.class forCellReuseIdentifier:@"HJBlacklistCell"];
    [self.tableView registerClass:HJBlacklistEditCell.class forCellReuseIdentifier:@"HJBlacklistEditCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 60;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = UIColor.whiteColor;
    [self.tableView setSectionIndexColor:UIColor.tj_9B9B9BColor];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView configuration:^TJEmptyDataType(TJEmptyDataModel * _Nonnull dataModel) {
        dataModel.text = @"No Blacklist Now";
        return TJEmptyDataTypeBase;
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleBacklistStateChangeNotification) name:backlistStateChangeNotification object:nil];
    [self loadData];
}

- (void)didClickRemoveButton {
    
    [HJAlertController alertInController:self title:@"Remove Blacklist" message:@"Are you sure about removing selected blacklist?" left:^(HJAlertAction * _Nonnull action) {
        action.title = @"Cancel";
        action.titleColor = UIColor.tj_868391Color;
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"OK";
        action.titleColor = UIColor.tj_mainColor;
        [action setHandler:^{
            [HJHUD showGraceTimeLoadingInView:self.view];
            [self deleteWithModels:self.selectDatas complete:^(NSError * _Nullable error) {
                if (!error) {
                    for (HJChatBlacklistModel *model in self.selectDatas) {
                        [self.datas removeObject:model];
                    }
                    [self.tableView reloadData];
                }
            }];
        }];
    }];
}

- (void)deleteWithModels:(NSArray *)models complete:(void (^__nullable)(NSError * _Nullable error))complete {
    
    NSMutableArray *userIds = [NSMutableArray array];
    for (HJChatBlacklistModel *model in models) {
        [userIds addObject:model.userId];
    }
    [HJMinePresent setBacklistWithUserIds:userIds backlist:NO complete:^(NSError * _Nullable error) {
        if (complete) {
            complete(error);
        }
        if (!error) {
            self.isEdit = NO;
            self.editButton.hidden = self.datas.count == 0;
        }
    }];
}

- (void)didClickSelectAllButton:(HJBarButton *)button {
    [self.selectDatas removeAllObjects];

    if (_isSelectAll) {
        for (HJChatBlacklistModel *model in self.datas) {
            model.isSelect = NO;
        }
        [button setTitle:@"Select all" forState:UIControlStateNormal];
        _isSelectAll = NO;
    } else {
        _isSelectAll = YES;
        for (HJChatBlacklistModel *model in self.datas) {
            model.isSelect = YES;
        }
        [self.selectDatas addObjectsFromArray:self.datas];
        [button setTitle:@"Cancel" forState:UIControlStateNormal];
    }
    
    [button sizeToFit];
    CGSize buttonSize = button.tj_size;
    [button mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(buttonSize.width);
    }];
    [self.tableView reloadData];
    
    if (self.selectDatas.count > 0) {
        [self showBottomView];
    } else {
        [self hiddenBottomView];
    }
}

- (void)didClickEditButton {
    self.isEdit = YES;
    self.navigationBar.backBarButton.selected = YES;
    [self.tableView reloadData];
}

- (void)popViewController {
    if (self.navigationBar.backBarButton.selected) {
        self.isEdit = NO;
    } else {
        [super popViewController];
    }
}

- (void)setIsEdit:(BOOL)isEdit {
    _isEdit = isEdit;
    
    _editButton.hidden = isEdit;
    _selectAllButton.hidden = !isEdit;
    
    if (!_isEdit) {
        [self hiddenBottomView];
        _isSelectAll = NO;
        for (HJChatBlacklistModel *model in self.datas) {
            model.isSelect = NO;
        }
        self.navigationBar.backBarButton.selected = NO;
        [self.selectDatas removeAllObjects];
        [self.tableView reloadData];
    }
}

- (void)handleBacklistStateChangeNotification {
    [self loadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isEdit) {
        HJBlacklistEditCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJBlacklistEditCell" forIndexPath:indexPath];
        cell.model = self.datas[indexPath.row];;
        return cell;
    }
    
    HJBlacklistCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJBlacklistCell" forIndexPath:indexPath];
    cell.model = self.datas[indexPath.row];;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJChatBlacklistModel *model = self.datas[indexPath.row];

    if (_isEdit) {
        model.isSelect = !model.isSelect;
        HJBlacklistCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.model = model;
        
        if (model.isSelect) {
            [self.selectDatas addObject:model];
        } else {
            if ([self.selectDatas containsObject:model]) {
                [self.selectDatas removeObject:model];
            }
        }
        
        
        if (self.selectDatas.count > 0) {
            [self showBottomView];
        } else {
            [self hiddenBottomView];
        }
        
        if (self.selectDatas.count == self.datas.count) {
            _isSelectAll = YES;
            [self.selectAllButton setTitle:@"Cancel" forState:UIControlStateNormal];
        } else {
            _isSelectAll = NO;
            [self.selectAllButton setTitle:@"Select all" forState:UIControlStateNormal];
        }
        [self.selectAllButton sizeToFit];
        CGSize buttonSize = self.selectAllButton.tj_size;
        [self.selectAllButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.inset(leftRightMargin);
            make.width.offset(buttonSize.width);
        }];
        return;
    }
    
    HJUserInfoController *infoController = [[HJUserInfoController alloc] init];
    infoController.userId = model.userId;
    [self.navigationController pushViewController:infoController];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return !_isEdit;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJWeakify(self)
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:nil handler:^(UIContextualAction * _Nonnull action, UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
    [weakself deleteConversationWithIndexPath:indexPath];
        completionHandler(YES);
    }];

    deleteAction.backgroundColor = UIColor.tj_FFEEE6Color;
    deleteAction.image = [UIImage imageNamed:@"cell_delete"];

    UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    return configuration;
}

- (void)deleteConversationWithIndexPath:(NSIndexPath *)indexPath {
    [HJAlertController alertInController:self title:@"Remove Blacklist" message:@"Are you sure about removing selected blacklist?" left:^(HJAlertAction * _Nonnull action) {
        action.title = @"Cancel";
        action.titleColor = UIColor.tj_868391Color;
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"OK";
        action.titleColor = UIColor.tj_mainColor;
        [action setHandler:^{
            HJChatSessionModel *model = self.datas[indexPath.row];
            [self deleteWithModels:@[model] complete:^(NSError * _Nullable error) {
                if (!error) {
                    [self.datas removeObject:model];
                    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }
            }];
            
        }];
    }];
}
 
- (void)showBottomView {
    if (!_buttoomView) {
        UIView *buttoomView = [UIView addToView:self.view];
        buttoomView.backgroundColor = UIColor.whiteColor;
        _buttoomView = buttoomView;
        
        UIView *lineView = [UIView addToView:buttoomView];
        lineView.backgroundColor = UIColor.tj_separatorColor;
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(0);
            make.top.offset(0);
            make.height.offset(lineHeight);
        }];
        
        HJButton *removeButton = [HJButton buttonWithSuperView:buttoomView font:UIFontMake(12) color: UIColor.tj_333333Color title:@"Remove"];
        [removeButton setImage:[UIImage imageNamed:@"blacklist_remove"] forState:UIControlStateNormal];
        removeButton.imagePosition = QMUIButtonImagePositionTop;
        removeButton.spacingBetweenImageAndTitle = 6;
        [removeButton addTarget:self action:@selector(didClickRemoveButton) forControlEvents:UIControlEventTouchUpInside];
        [removeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(60);
            make.top.offset(0);
            make.centerX.offset(0);
        }];
    }
    
    CGFloat H = TabbarSafeBottomMargin + 60;

    if (_isShowBottomView) {
        return;
    }
    _isShowBottomView = YES;
    self.buttoomView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, H);
    [UIView animateWithDuration:0.25 animations:^{
        self.buttoomView.frame = CGRectMake(0, KScreenHeight - H, KScreenWidth, H);
    }];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, H, 0);
}


- (void)hiddenBottomView {
    [UIView animateWithDuration:0.25 animations:^{
        self.buttoomView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, self.buttoomView.tj_size.height);
    }];
    _isShowBottomView = NO;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)loadData {
    [HJMinePresent loadBlacklistListDataComplete:^(NSArray * _Nullable datas, HJLoadType loadType) {
        if (loadType == HJLoadTypeNetwork) {
            self.emptyDataHandler.canDisplay = YES;
        }

        [self hiddenLoading];
        [self.datas removeAllObjects];
        if (datas.count) {
            self.editButton.alpha = 1;
            [self.datas addObjectsFromArray:datas];
        }
        self.editButton.hidden = self.datas.count == 0;
        [self.tableView reloadData];
    }];
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)selectDatas {
    if (!_selectDatas) {
        _selectDatas = [NSMutableArray array];
    }
    return _selectDatas;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end


